package com.yuanxin.chooseimage.imagechoosemodule;

import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.yalantis.ucrop.UCrop;
import com.yuanxin.chooseimage.R;
import com.yuanxin.chooseimage.customutil.ImageUtil;
import com.yuanxin.chooseimage.customutil.LocalUtil;
import com.yuanxin.chooseimage.imagechoosemodule.bean.Image;
import com.yuanxin.chooseimage.imagechoosemodule.utils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 多图选择
 * Created by Nereo on 2015/4/7.
 * Updated by nereo on 2016/1/19.
 */
public class MultiImageSelectorActivity extends FragmentActivity {

    public final String TAG = "MultiActivity";

    /**
     * 最大图片选择次数，int类型，默认9
     */
    public static final String EXTRA_SELECT_COUNT = "max_select_count";
    /**
     * 图片选择模式，默认多选
     */
    public static final String EXTRA_SELECT_MODE = "select_count_mode";
    /**
     * 是否显示相机，默认显示
     */
    public static final String EXTRA_SHOW_CAMERA = "show_camera";
    /**
     * 显示图片,视频
     */
    public static final String EXTRA_SHOW_PIC_VIDEO = "show_pic_video";
    /**
     * 是否需要剪切
     */
    public static final String EXTRA_IS_CUT = "is_cut";
    /**
     * 剪切宽度
     */
    public static final String EXTRA_CUT_WIDTH = "cut_width";
    /**
     * 剪切高度
     */
    public static final String EXTRA_CUT_HEIGHT = "cut_height";

    /**
     * 选择结果，返回为 ArrayList&lt;String&gt; 图片路径集合
     */
    public static final String EXTRA_RESULT = "select_result";
    /**
     * 默认选择集
     */
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "default_list";
    public static final int PIC_CUT = 3;
    /**
     * 单选
     */
    public static final int MODE_SINGLE = 0;
    /**
     * 多选
     */
    public static final int MODE_MULTI = 1;
    /**
     * 视频录制的时长
     */
    public static final String EXTRA_MAX_SECOND = "max_second";

    private ArrayList<Image> resultImageList = new ArrayList<Image>();
    private ArrayList<String> resultVideoList = new ArrayList<String>();
    private Button mSubmitButton;
    private int mDefaultCount;
    private TextView tv_pic_video;
    private int isPicVideo;
    private boolean isCut = false;
    private int cutHeight;
    private int cutWidth;
    private int maxSecond;

    MultiImageSelectorFragment fragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.black));
        }
        setContentView(R.layout.activity_default);

        // 完成按钮
        mSubmitButton = (Button) findViewById(R.id.commit);
        mSubmitButton.setText(R.string.action_done);

        Intent intent = getIntent();
        mDefaultCount = intent.getIntExtra(EXTRA_SELECT_COUNT, 9);
        isCut = intent.getBooleanExtra(EXTRA_IS_CUT, false);
        int mode = intent.getIntExtra(EXTRA_SELECT_MODE, MODE_MULTI);
        boolean isShow = intent.getBooleanExtra(EXTRA_SHOW_CAMERA, true);
        isPicVideo = intent.getIntExtra(EXTRA_SHOW_PIC_VIDEO, 0);
        cutHeight = intent.getIntExtra(EXTRA_CUT_HEIGHT, 0);
        cutWidth = intent.getIntExtra(EXTRA_CUT_WIDTH, 0);
        if(isPicVideo==1){
            maxSecond=intent.getIntExtra(EXTRA_MAX_SECOND,0);
        }
         //Log.e(TAG, "isShow-1--" + isShow + "---isPicVideo-1--" + isPicVideo+"--maxSecond---"+maxSecond);

        if (mode == MODE_MULTI && intent.hasExtra(EXTRA_DEFAULT_SELECTED_LIST)) {
            resultImageList = (ArrayList<Image>) intent.getSerializableExtra(EXTRA_DEFAULT_SELECTED_LIST);
        }


        // 返回按钮
        findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });


        //图片，视频
        tv_pic_video = (TextView) findViewById(R.id.tv_pic_video);
        if (isPicVideo == 0) {
            tv_pic_video.setText("图片");
            if (resultImageList == null || resultImageList.size() <= 0) {
                mSubmitButton.setEnabled(false);
            } else {
                updateDoneText(resultImageList.size());
                mSubmitButton.setEnabled(true);
            }
        } else if (isPicVideo == 1) {
            tv_pic_video.setText("视频");
            mDefaultCount = 1;//如果是视频，每次最多只能选择一个
            if (resultVideoList == null || resultVideoList.size() <= 0) {
                mSubmitButton.setEnabled(false);
            } else {
                updateDoneText(resultVideoList.size());
                mSubmitButton.setEnabled(true);
            }
        }


        mSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent data = new Intent();
                if (isPicVideo == 0) {//图片
                    if (resultImageList != null && resultImageList.size() > 0) {
                        for (int i = 0; i < resultImageList.size(); i++) {
                            Image image = resultImageList.get(i);
                            int rotationAngle = 0;
                            try {
                                rotationAngle = ImageUtil.readPictureDegree(image.filePath);
                            } catch (IOException e) {
                                e.printStackTrace();
                                // Log.i(TAG, "这个文件损坏，过滤掉");
                                //这个文件损坏，过滤掉
                                resultImageList.remove(image);
                                continue;
                            }
                            Bitmap bitmap = BitmapFactory.decodeFile(image.filePath);
                            if (bitmap == null) {
                                resultImageList.remove(image);
                                continue;
                            } else {
                                if (rotationAngle > 0) {
                                    ImageUtil.compressBitmap(image.filePath);
                                    Bitmap newBitmap = ImageUtil.rotateBitmap(bitmap, rotationAngle);
                                    bitmap.recycle();
                                    try {
                                        FileOutputStream fos = new FileOutputStream(image.filePath);
                                        newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                                        fos.flush();
                                        fos.close();
                                        bitmap = newBitmap;
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        LocalUtil.PromiseReject(ex);
                                    }
                                }
                                image.setWidth(bitmap.getWidth());
                                image.setHeight(bitmap.getHeight());
                                bitmap.recycle();
                            }
                        }
                        // 返回已选择的图片数据
                        data.putExtra(EXTRA_RESULT, resultImageList);
                        setResult(RESULT_OK, data);
                    } else {
                        setResult(RESULT_CANCELED);
                    }
                    finish();
                } else {//视频
                    if (resultVideoList != null && resultVideoList.size() > 0) {
                        data.putExtra("filePath", resultVideoList.get(0));
                        setResult(RESULT_OK, data);
                    } else {
                        setResult(RESULT_CANCELED);
                    }
                    finish();
                }
            }
        });


        Bundle bundle = new Bundle();
        bundle.putInt(MultiImageSelectorFragment.EXTRA_SELECT_COUNT, mDefaultCount);
        bundle.putInt(MultiImageSelectorFragment.EXTRA_SELECT_MODE, mode);
        bundle.putBoolean(MultiImageSelectorFragment.EXTRA_SHOW_CAMERA, isShow);
        bundle.putInt(MultiImageSelectorFragment.EXTRA_SHOW_PIC_VIDEO, isPicVideo);
        bundle.putInt(MultiImageSelectorFragment.EXTRA_CUT_WIDTH, cutHeight);
        bundle.putInt(MultiImageSelectorFragment.EXTRA_CUT_HEIGHT, cutWidth);
        bundle.putInt(MultiImageSelectorFragment.EXTRA_MAX_SECOND, maxSecond);
        bundle.putSerializable(MultiImageSelectorFragment.EXTRA_DEFAULT_IMAGE_SELECTED_LIST, resultImageList);
        bundle.putStringArrayList(MultiImageSelectorFragment.EXTRA_DEFAULT_VIDEO_SELECTED_LIST, resultVideoList);

        fragment = new MultiImageSelectorFragment();
        fragment.setArguments(bundle);
        fragment.setHandler(handler);

        getSupportFragmentManager().beginTransaction()
                .add(R.id.image_grid, fragment)
                .commit();

    }

    public void updateDoneText(int count) {
        mSubmitButton.setText(String.format("%s(%d/%d)",
                getString(R.string.action_done), count, mDefaultCount));
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mSubmitButton.setText(msg.obj.toString());
            if (msg.arg1 == 0) {
                mSubmitButton.setText(R.string.action_done);
                mSubmitButton.setEnabled(false);
            } else {
                if (!mSubmitButton.isEnabled()) {
                    mSubmitButton.setEnabled(true);
                }
            }
        }
    };

    public void onCameraShot(File imageFile) {
        if (imageFile != null) {
            String picFilePath = imageFile.getAbsolutePath();
            int rotationAngle = 0;
            try {
                rotationAngle = ImageUtil.readPictureDegree(picFilePath);
            } catch (IOException e) {
                e.printStackTrace();
                LocalUtil.PromiseReject(e);
                finish();
                return;
            }
            ImageUtil.compressBitmap(picFilePath);
            Bitmap bitmap = BitmapFactory.decodeFile(picFilePath);
            if (rotationAngle > 0) {
                Bitmap newBitmap = ImageUtil.rotateBitmap(bitmap, rotationAngle);
                bitmap.recycle();
                try {
                    FileOutputStream fos = new FileOutputStream(picFilePath);
                    newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                    bitmap = newBitmap;
                    imageFile = new File(picFilePath);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    LocalUtil.PromiseReject(ex);
                    finish();
                    return;
                }
            }


            // notify system
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));
            Intent data = new Intent();
            resultImageList.add(new Image(imageFile.getAbsolutePath(), bitmap.getWidth(), bitmap.getHeight()));

            data.putExtra(EXTRA_RESULT, resultImageList);
            setResult(RESULT_OK, data);

            finish();
        }
    }

    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = null;
        if (Build.VERSION.SDK_INT < 11) {
            actualimagecursor = managedQuery(uri, proj, null, null, null);
        } else {
            CursorLoader cursorLoader = new CursorLoader(this, uri, null, null, null, null);
            actualimagecursor = cursorLoader.loadInBackground();
        }
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case MultiImageSelectorFragment.REQUEST_CAMERA:
                if (resultCode == RESULT_OK) {
                    if (isPicVideo == 0) {//图片
                        if (isCut) {
                            startCropImageIntent(MultiImageSelectorFragment.mTmpFile.getAbsolutePath());
                        } else if (MultiImageSelectorFragment.mTmpFile != null && this != null)
                            onCameraShot(MultiImageSelectorFragment.mTmpFile);
                    } else {//视频
                        if (MultiImageSelectorFragment.mTmpFile != null && this != null) {
                            Intent intent = new Intent();
                            intent.putExtra("filePath", MultiImageSelectorFragment.mTmpFile.getAbsolutePath());
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }
                } else {
                    while (MultiImageSelectorFragment.mTmpFile != null && MultiImageSelectorFragment.mTmpFile.exists()) {
                        if (MultiImageSelectorFragment.mTmpFile.delete())
                            MultiImageSelectorFragment.mTmpFile = null;
                    }
                }
                break;
//            case PIC_CUT:
//                if (MultiImageSelectorFragment.mTmpFile != null && this != null) {
//                    onCameraShot(MultiImageSelectorFragment.mTmpFile);
//                }
//                break;
            case UCrop.REQUEST_CROP:
                Uri resultUri = UCrop.getOutput(data);
                if (resultUri != null && this != null) {
                    onCameraShot(uri2File(resultUri));
                }
                break;
            case UCrop.RESULT_ERROR:
                LocalUtil.PromiseReject(UCrop.getError(data));
                setResult(UCrop.RESULT_ERROR);
                finish();
                break;
            default:
                if (MultiImageSelectorFragment.mTmpFile != null && this != null) {
                    onCameraShot(MultiImageSelectorFragment.mTmpFile);
                }
                break;
        }
    }

    public void startCropImageIntent(String path) {
        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(new File(path));
        } else {
            uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", new File(path));
        }
        int color = Color.parseColor("#21282C");//这个颜色和图片列表一致
        UCrop.Options options = new UCrop.Options();
        options.setCropFrameStrokeWidth(2);//裁剪框线的所需宽度（像素）
        options.setCropGridStrokeWidth(2);//网格线的所需宽度（像素）
        options.setActiveWidgetColor(color);//横向滑轮颜色
        options.setToolbarColor(color);//导航栏颜色
        options.setLogoColor(color);//logo颜色 注意，这个logo一闪而过
        options.setRootViewBackgroundColor(color);// 背景色
        options.setToolbarWidgetColor(Color.WHITE);//导航栏按钮色
        options.setStatusBarColor(color);//状态栏颜色
        options.withAspectRatio(1, 1);//宽高比
        options.withMaxResultSize(cutWidth == 0 ? 300 : cutWidth * 2, cutHeight == 0 ? 300 : cutHeight * 2);
        File file = null;
        try {
            file = FileUtils.createTmpFilePic(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        UCrop.of(uri, Uri.fromFile(file))
                .withOptions(options)
                .start(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
